package grouplife::Controller::StoresCreate;
use Moose;
use namespace::autoclean;
use Catalyst qw/
Session
Session::Store::FastMmap
Session::State::Cookie
/;
use Util::Taobao::StoresCreate;
use Util::Taobao::QueryStoreInfo;
use Util::Taobao::CreateTaobaoStores;
use grouplife::Model::Store::StoreSearchModel;
use grouplife::Model::Store::StoreCreateModel;
use grouplife::Model::Category::CategoryModel;
use grouplife::Model::Leimu::LeimuModel;
use grouplife::Model::UserStore::UserStoreModel;
use grouplife::Model::LeimuCategory::LeimuCategoryModel;
use grouplife::Model::CommentedItem::CommentedItemModel;
use Data::Dumper;


BEGIN {extends 'Catalyst::Controller'; }
__PACKAGE__->config( 'Plugin::ConfigLoader' => { file => 'grouplife.yml' } );

=head1 NAME

grouplife::Controller::Login - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut


sub load_stores :Path('load_stores') :Args(0) {
	my ($self, $c) = @_;
	my $storeIds = $c->request->params->{"storeId[]"};
	my $size = 0;
	if(ref($storeIds) eq 'ARRAY') { 
		$size = scalar(@$storeIds);
	} else {
		my @arr = ($storeIds);
		$storeIds = \@arr;
	}
	my $rounds = int($size / 20);
	$rounds = $rounds ; 
	my $left = $size % 20;
	
	my $redirect_uri = $c->config->{redirect_uri};
	my $app_key = $c->config->{app_key};
        my $secret_key = $c->config->{secret_key};
        my $gateway_url = $c->config->{gateway_url};
        my $oauth_url = $c->config->{oauth_url};
        my $version = $c->config->{version};
	my $user = $c->session->{login_user};

#Need to split storeIds into a batch of 20 and process those batches one by one
	my $count = 0;
	my $storeInfoLoader = Util::Taobao::QueryStoreInfo->new();	
	my $storeCreator = Util::Taobao::CreateTaobaoStores->new();
	my $catModel = $c->model('Category::CategoryModel'); 
	my $leimuModel = $c->model('Leimu::LeimuModel'); 
	my $storeCreateModel = $c->model('Store::StoreCreateModel'); 
	my $storeSearchModel = $c->model('Store::StoreSearchModel'); 
	my $leimuCatModel = $c->model('LeimuCategory::LeimuCategoryModel');
	my $userStoreModel = $c->model('UserStore::UserStoreModel');
	my $commedItemModel = $c->model('CommentedItem::CommentedItemModel');
	my $returncode = 0;
	my $resData;
	if($size < 20) {
			($resData, $returncode) = $storeInfoLoader->get_stores_info($app_key, $secret_key, $gateway_url, $redirect_uri, $oauth_url, $version, $storeIds);
			$storeCreator->create_store($user->id, $app_key, $secret_key, $gateway_url, $redirect_uri, $oauth_url, $version, $resData, $catModel, $leimuModel, $leimuCatModel, $commedItemModel, $storeCreateModel, $storeSearchModel, $userStoreModel);		
	} else {
		while($count < $rounds) {
			my $start = $count * 20;
			my $end = $start + 19;
			my @numslice = @$storeIds[$start..$end];
			($resData, $returncode) = $storeInfoLoader->get_stores_info($app_key, $secret_key, $gateway_url, $redirect_uri, $oauth_url, $version, \@numslice);
			last if($returncode == 1);
			$count = $count + 1;
			$storeCreator->create_store($user->id, $app_key, $secret_key, $gateway_url, $redirect_uri, $oauth_url, $version, $resData, $catModel, $leimuModel, $leimuCatModel, $commedItemModel, $storeCreateModel, $storeSearchModel, $userStoreModel);		
		}

		if($left > 0) {
			my $start = $count * 20;		
			my $end = $start + $left - 1;
			my @numslice = @$storeIds[$start..$end];
			my ($resData, $returncode) = $storeInfoLoader->get_stores_info($app_key, $secret_key, $gateway_url, $redirect_uri, $oauth_url, $version, \@numslice);
			$storeCreator->create_store($user->id, $app_key, $secret_key, $gateway_url, $redirect_uri, $oauth_url, $version, $resData, $catModel, $leimuModel, $leimuCatModel, $commedItemModel, $storeCreateModel, $storeSearchModel, $userStoreModel);		
		}
	}
	if($returncode == 0) {
		$c->stash(css => 'zhuce.css');
		$c->stash(size => $size);
		$c->stash(name => $user->username);
		$c->stash(user_id => $user->id);
		$c->stash(login_user => $user);
		$c->stash(template => 'taobao/load_confirm_success.tt2');
	} else {
		$c->stash(css => 'zhuce.css');
		$c->stash(size => $size);
		$c->stash(name => $user->username);
		$c->stash(login_user => $user);
		$c->stash(user_id => $user->id);
		$c->stash(template => 'taobao/load_confirm_failure.tt2');
	}
}

sub index :Path :Args(0) {
	my ($self, $c) = @_;

# Get the username and password from form
	my $code= $c->request->params->{code} || '0';
	my $error= $c->request->params->{error} || '0';
	my $redirect_uri = $c->config->{redirect_uri}; 
	my $app_key = $c->config->{app_key};
	my $secret_key = $c->config->{secret_key};
	my $gateway_url = $c->config->{gateway_url};
	my $oauth_url = $c->config->{oauth_url};
	my $version = $c->config->{version};
	chomp $error;

	my $flag = 0;
	if($error eq '0') {
		my $authenticator = Util::Taobao::Authenticate->new();
		my $user = $authenticator->get_userinfo($code, $app_key, $secret_key, $gateway_url, $redirect_uri, $oauth_url, $version);

		if($user->{code} == 0) {
			my @users = $c->model('Users::UsersSearchModel')->get_user_by_nick('1', $user->{nick}); 

			my @bind_users;
			foreach my $u (@users) {
				if($u->active eq 'N') {
					$u->delete;
				}
				if($u->active eq 'Y') {
					push(@bind_users, $u);
				}
			}
			my $length = scalar(@bind_users);
			if ($length == 0) {
				$flag = 1;
				#Returned stores whose picked = 'R' or 'Y'
				#my @stores = $c->model('Store::StoreSearchModel')->get_unpicked_by_nick($user->{nick});
				#foreach my $store (@stores) {
				#	 $store->update({owner_email => $user->{email}, picked => 'Y'});	
				#}
				$c->stash(nick  =>  $user->{nick});
				$c->stash(css => 'zhuce.css');
				$c->stash(javascript => '/user/form_create.js');
				$c->stash(template => 'taobao/taobao_bind_storesCreate.tt2');
			} else {
				#if( ($bind_users[0]->active eq 'Y') and ($user->{nick} eq $bind_users[0]->source_nick) and ($bind_users[0]->source_id eq '1')) {
					my $auth_user = $c->find_user({ id => $bind_users[0]->id });
					$c->set_authenticated($auth_user);
					$c->session->{login_user} = $bind_users[0];
					my $storesCreator = Util::Taobao::StoresCreate->new();
					my $storeSearchModel = $c->model('Store::StoreSearchModel');
					my ($resData, $returncode) = $storesCreator->get_stores($user->{session}, $code, $app_key, $secret_key, $gateway_url, $redirect_uri, $oauth_url, $version, $storeSearchModel);
					if($returncode == 0) {
						$flag = 1;
						$c->stash(nick  =>  $user->{nick});
						$c->stash(email =>  $bind_users[0]->email_address);
						$c->stash(user =>  $bind_users[0]);
						$c->stash(css => 'zhuce.css');
						$c->stash(babies => $resData);
						$c->stash(login_user => $c->session->{login_user});
						$c->stash(javascript => '/taobao/load_stores.js');
						$c->stash(template => 'taobao/taobao_storesCreate.tt2');
					}
				#} else {
				#	$c->stash(nick  =>  $user->{nick});
				#	$c->stash(email =>  $bind_users[0]->email_address);
				#	$c->stash(user =>  $bind_users[0]);
				#	$c->stash(css => 'zhuce.css');
				#	$c->stash(template => 'taobao/taobao_bind.tt2');
				#}
			}

		}
	} 
	unless($flag == 1) {
		$c->stash(css => 'zhuce.css');
		$c->stash(template => 'taobao/taobao_bind_failure.tt2');
	}
}
=head1 AUTHOR

lijie,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
